package com.gl.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gl.common.exception.ServiceException;
import com.gl.common.vo.MyUtils;
import com.gl.common.vo.PageObject;
import com.gl.common.vo.ProductVo;
import com.gl.dao.ProductDao;
import com.gl.pojo.Product;
import com.gl.service.ProductService;
/**
 *	商品详情业务实现类 
 * @author FengLong
 */
@Service
public class ProductServiceImpl implements ProductService{
	int pageSize = 9;
	@Autowired
	private ProductDao productDao;
	/**前台分页*/
	@Override
	public PageObject<ProductVo> findPageProducts(String name, Integer pageCurrent) {
		//参数校验
		int startIndex =doCheckArgument(name, pageCurrent);
		List<ProductVo> records=
				productDao.findPageProducts(
						name, startIndex, pageSize);
		//4.封装结果并返回
		return new PageObject<>(productDao.getRowCount(name), 
				records, pageCurrent, pageSize);
	}

	/**前台详情*/
	@Override
	public Product findProductById(Integer id) {
		if(id<=0)
			throw new IllegalArgumentException("id值不正确");
		Product p = productDao.findProductById(id);
		if(p==null)
			throw new ServiceException("该记录可能不存在");
		return  p;
	}
	/**后台删除*/
	@Override
	public int deleteProduct(Integer[] ids) {
		//参数校验
		if(ids==null||ids.length==0)
			throw new IllegalArgumentException("请先选中要删除的对象");
		int rows = productDao.deleteProductByIds(ids);
		//提供数据不存在异常
		if(rows==0)
			throw new ServiceException("删除失败,该记录可能已经不存在");
		return rows;
	}
	/**后台分页*/
	@Override
	public PageObject<Product> findSysPageProducts(String name, Integer pageCurrent) {
		//参数校验
		int startIndex = doCheckArgument(name, pageCurrent);
		List<Product> records = productDao.findSysPageProducts(
				name, startIndex, pageSize);
		//4.封装结果并返回
		return new PageObject<>(productDao.getRowCount(name), 
				records, pageCurrent, pageSize);
	}
	/**后台修改*/
	@Override
	public int updateProduct(Product entity) {
		//参数校验
		MyUtils.doCheckEntity(entity);
		return productDao.updateProductById(entity);
	}
	/**后台新增*/
	@Override
	public int saveProduct(Product entity) {
		//参数校验
		MyUtils.doCheckEntity(entity);
		int rows = productDao.insertProduct(entity);
		return rows;
	}

	/**
	 *	参数校验方法
	 */
	private int doCheckArgument(String name, Integer pageCurrent) {
		//校验参数
		if(pageCurrent==null||pageCurrent<1)
			throw new ServiceException("当前页码值不正确");
		//获取总记录数
		//int rowCount = productDao.getRowCount(name);
		if(productDao.getRowCount(name)<=0)
			throw new ServiceException("该记录不存在");
		//3.查询当前页记录
		int startIndex=(pageCurrent-1)*pageSize;
		return startIndex;
	}
}
